<template>
  <div class="login">
    <div class="container">
      <div class="login-content">
        <div class="platform-info">
          <h1 class="platform-title">工业电商平台</h1>
          <p class="platform-subtitle">专业机械工业品采购平台</p>
        </div>

        <div class="login-card card">
          <div class="login-header">
            <h2 class="login-title">用户登录</h2>
            <p class="login-subtitle">请输入您的账号和密码</p>
          </div>

          <form @submit.prevent="handleLogin" class="login-form">
            <div class="form-group">
              <label for="username" class="form-label">用户名</label>
              <input
                  id="username"
                  v-model.trim="username"
                  type="text"
                  class="input"
                  placeholder="请输入用户名"
                  required
                  @input="clearError"
              />
            </div>

            <div class="form-group">
              <label for="password" class="form-label">密码</label>
              <input
                  id="password"
                  v-model="password"
                  type="password"
                  class="input"
                  placeholder="请输入密码"
                  required
                  @input="clearError"
              />
            </div>

            <div class="login-options">
              <label class="remember-me">
                <input type="checkbox" v-model="rememberMe" />
                <span>记住我</span>
              </label>
              <a href="#" class="forgot-password">忘记密码？</a>
            </div>

            <button type="submit" :disabled="isLoading" class="btn btn-primary btn-lg w-full">
              <span v-if="isLoading" class="loading-spinner"></span>
              {{ isLoading ? '登录中...' : '登录' }}
            </button>

            <div class="register-link">
              <span>还没有账号？</span>
              <router-link to="/register" class="link">立即注册</router-link>
            </div>

            <div v-if="errorMessage" class="error">
              <svg class="error-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <line x1="15" y1="9" x2="9" y2="15"/>
                <line x1="9" y1="9" x2="15" y2="15"/>
              </svg>
              {{ errorMessage }}
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import request from '../../utils/request';

// 响应式数据
const username = ref('');
const password = ref('');
const rememberMe = ref(false);
const isLoading = ref(false);
const errorMessage = ref('');

// 获取router和store
const router = useRouter();
const store = useStore();

// 方法
const clearError = () => {
  errorMessage.value = '';
};

const validateInput = () => {
  if (!username.value) {
    errorMessage.value = '请输入用户名';
    return false;
  }
  if (!password.value) {
    errorMessage.value = '请输入密码';
    return false;
  }
  return true;
};

const handleLogin = async () => {
  if (!validateInput()) return;

  isLoading.value = true;
  errorMessage.value = '';

  try {
    const response = await request.post('/user/login', {
      username: username.value,
      password: password.value
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (response.data.status === 200) {
      const user = response.data.user;

      // 保存到localStorage
      localStorage.setItem('user', JSON.stringify(user));

      // 更新store中的用户状态
      store.dispatch('login', user);

      // 获取用户购物车数据
      await store.dispatch('fetchCartItems');

      // 根据用户角色决定跳转路径
      if (user.isAdmin === 1) {
        // 管理员跳转到后台管理
        router.push('/admin');
      } else {
        // 普通用户跳转到首页
        router.push('/home');
      }
      router.push('/home');
    } else {
      errorMessage.value = response.data.msg || '登录失败';
    }
  } catch (error) {
    console.error('登录错误:', error);
    if (error.response) {
      if (error.response.status === 401) {
        errorMessage.value = '用户名或密码错误';
      } else {
        errorMessage.value = `服务器错误 (${error.response.status})`;
      }
    } else {
      errorMessage.value = '网络错误，请检查您的连接';
    }
  } finally {
    isLoading.value = false;
  }
};

const handleLoginSuccess = (response) => {
  const user = response.data.user;
  localStorage.setItem('user', JSON.stringify(user));
  store.dispatch('login', user);
  router.push('/home');
};

const handleLoginFailure = (response) => {
  errorMessage.value = response.data.message || '用户名或密码错误';
};

const handleRequestError = (error) => {
  console.error('登录错误:', error);
  if (error.response) {
    const status = error.response.status;
    if (status === 400) {
      errorMessage.value = '请求格式错误，请联系管理员';
    } else if (status === 401) {
      errorMessage.value = '用户名或密码错误';
    } else {
      errorMessage.value = `服务器错误 (${status})`;
    }
  } else {
    errorMessage.value = '网络错误，请检查您的连接';
  }
};
</script>

<style scoped>
.login {
  min-height: 100vh;
  background-color: var(--gray-50);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-8) 0;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--spacing-12);
  width: 100%;
}

.platform-info {
  text-align: center;
}

.platform-title {
  font-size: var(--font-size-4xl);
  font-weight: var(--font-weight-bold);
  color: var(--gray-900);
  margin: 0 0 var(--spacing-2) 0;
  line-height: var(--line-height-tight);
}

.platform-subtitle {
  font-size: var(--font-size-lg);
  color: var(--gray-600);
  margin: 0;
}

.login-card {
  width: 100%;
  max-width: 480px;
  padding: 0;
  border: none;
}

.login-header {
  padding: var(--spacing-8);
  text-align: center;
  border-bottom: 1px solid var(--gray-200);
}

.login-title {
  font-size: var(--font-size-2xl);
  font-weight: var(--font-weight-bold);
  color: var(--gray-900);
  margin: 0 0 var(--spacing-2) 0;
}

.login-subtitle {
  font-size: var(--font-size-base);
  color: var(--gray-600);
  margin: 0;
}

.login-form {
  padding: var(--spacing-8);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-6);
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2);
}

.form-label {
  font-weight: var(--font-weight-medium);
  color: var(--gray-700);
  font-size: var(--font-size-sm);
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: var(--spacing-2) 0;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: var(--spacing-2);
  font-size: var(--font-size-sm);
  color: var(--gray-600);
  cursor: pointer;
}

.remember-me input[type="checkbox"] {
  width: 16px;
  height: 16px;
  accent-color: var(--primary-color);
}

.forgot-password {
  font-size: var(--font-size-sm);
  color: var(--primary-color);
  text-decoration: none;
  transition: color var(--transition-fast);
}

.forgot-password:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

.register-link {
  text-align: center;
  font-size: var(--font-size-sm);
  color: var(--gray-600);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-1);
}

.link {
  color: var(--primary-color);
  text-decoration: none;
  font-weight: var(--font-weight-medium);
  transition: color var(--transition-fast);
}

.link:hover {
  color: var(--primary-hover);
  text-decoration: underline;
}

.error {
  display: flex;
  align-items: center;
  gap: var(--spacing-2);
  color: var(--error-color);
  font-size: var(--font-size-sm);
  padding: var(--spacing-3);
  background-color: #fee2e2;
  border: 1px solid #fecaca;
  border-radius: var(--radius-md);
}

.error-icon {
  width: 16px;
  height: 16px;
  stroke: currentColor;
  fill: none;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login {
    padding: var(--spacing-4);
  }

  .login-content {
    gap: var(--spacing-8);
  }

  .platform-title {
    font-size: var(--font-size-3xl);
  }

  .platform-subtitle {
    font-size: var(--font-size-base);
  }

  .login-header {
    padding: var(--spacing-6);
  }

  .login-form {
    padding: var(--spacing-6);
  }
}

@media (max-width: 480px) {
  .platform-title {
    font-size: var(--font-size-2xl);
  }

  .login-title {
    font-size: var(--font-size-xl);
  }

  .login-options {
    flex-direction: column;
    gap: var(--spacing-3);
    align-items: flex-start;
  }
}
</style>